package com.robot.mq.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import entity.weixin.WeiXin;
import entity.weixin.template.PaySuccess;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import util.HttpUtil;

import java.util.LinkedList;
import java.util.List;

/**
 * @author wuyunbin
 */
public class WeChatNotifyHandler {
    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String secret;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public void sendMessageToUser(String notify) {
        //请求地址
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId("wx6246e0503023027f");
        wxStorage.setSecret("32fbd5b25c909873d357d6105b7dd441");
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);

        logger.info(wxStorage.toString());

        //1.数据


        String[] notifyArray=notify.split("-notify-");
        String type=notifyArray[0];
        if(type.contains("PaySuccess")){
            PaySuccess paySuccess=JSON.parseObject(notifyArray[1],PaySuccess.class);
            logger.info(paySuccess.toString());
            List<WxMpTemplateData> list = new LinkedList<>();
            list.add(new WxMpTemplateData("first",paySuccess.getFirst()));
            list.add(new WxMpTemplateData("keyword1",paySuccess.getKeyword1()));
            list.add(new WxMpTemplateData("keyword2",paySuccess.getKeyword2()));
            list.add(new WxMpTemplateData("keyword3",paySuccess.getKeyword3()));
            list.add(new WxMpTemplateData("keyword4",paySuccess.getKeyword4()));
            list.add(new WxMpTemplateData("keyword5",paySuccess.getKeyword5()));
            list.add(new WxMpTemplateData("remark",paySuccess.getRemark()));

            //2.推送消息
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(paySuccess.getRecipient())
                    .data(list)
                    .templateId(paySuccess.getTemplateId())
                    .url("http://merchant.mashangjie.shop/")
                    .build();
            //3.发起推送
            try {
                String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                logger.info("推送成功：" + msg);
            } catch (Exception e) {
                logger.info("推送失败：" + e.getMessage());
                e.printStackTrace();
            }
        }




    }

//    public void sendMessageToAllUser(WeChatNotify weChatNotify) {
//        //请求地址
//        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
//        wxStorage.setAppId(appId);
//        wxStorage.setSecret(secret);
//        WxMpService wxMpService = new WxMpServiceImpl();
//        wxMpService.setWxMpConfigStorage(wxStorage);
//
//        //1.数据
//        List<WxMpTemplateData> data = noticeData(String[])weChatNotify.getData());
//        logger.info("data=" + data);
//
//        List<String> list = getAttentionList();
//        logger.info("wechat's user list=" + list);
//        for (String s : list) {
//            //2.推送消息
//            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
//                    .toUser(s)
//                    .data(data)
//                    .templateId(templateId)
//                    .url("http://member.mashangjie.shop/")
//                    .build();
//            //3.发起推送
//            try {
//                String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
//                logger.info("推送成功：" + msg);
//            } catch (Exception e) {
//                logger.info("推送失败：" + e.getMessage());
//                e.printStackTrace();
//            }
//        }
//    }

    private List<String> getAttentionList() {
        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        String result = HttpUtil.httpRequest(url);
        //返回结果的json对象
        JSONObject resultObject = JSON.parseObject(result);
        //请求获取userInfo
        String infoUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + resultObject.getString("access_token");
        String resultInfo = HttpUtil.httpRequest(infoUrl);
        //此时已获取到userInfo，再根据业务进行处理
        WeiXin weiXin = JSON.parseObject(resultInfo, WeiXin.class);
        return weiXin.getData().getOpenid();
    }
}
